<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<title>问卷题目管理</title>
	<link rel="stylesheet" href="../../lib/element-ui/theme-chalk/index.css">
	<link rel="stylesheet" href="../../lib/vxe-table/index.css">
	<link rel="stylesheet" href="../../lib/vxe-table-plugin-element/style.css">
	<link rel="stylesheet" href="../../lib/font-awesome/css/font-awesome.min.css">
	<script type="text/javascript" src="../../lib/vue/vue.js"></script>
	<script type="text/javascript" src="../../lib/xe-utils/xe-utils.js"></script>
	<script type="text/javascript" src="../../lib/element-ui/index.js"></script>
	<script type="text/javascript" src="../../lib/vxe-table/index.js"></script>
	<script type="text/javascript" src="../../lib/vxe-table-plugin-element/index.js"></script>
	<script type="text/javascript" src="../../lib/xlsx/xlsx.full.min.js"></script>
	<script type="text/javascript" src="../../lib/vxe-table-plugin-export-xlsx/index.min.js"></script>
	<script type="text/javascript" src="../../lib/xe-ajax/xe-ajax.js"></script>
	<script type="text/javascript" src="../../static/js/jquery.min.js"></script>
	<script type="text/javascript" src="../../static/js/webApi.js"></script>
	<script type="text/javascript" src="../../static/js/tool.js"></script>
	<style type="text/css">
		/*
		        找到html标签、body标签，和挂载的标签
		        都给他们统一设置样式
		    */
		html,
		body,
		#app,
		.el-container {
			/*设置内部填充为0，几个布局元素之间没有间距*/
			padding: 0px;
			/*外部间距也是如此设置*/
			margin: 0px;
			/*统一设置高度为100%*/
			height: 100%;
		}

		.el-main {
			padding: 4px;
		}

		[v-cloak] {
			display: none !important;
		}
	</style>
</head>

<body>
	<el-container id="app">
		<el-main>
			<div v-cloak>
				<el-form :inline="true" ref="queryData" label-width="70px" label-position="right" size="mini"
					style="height: 35px;text-align:right;">
					<el-form-item>
						<el-button type="info" icon="el-icon-refresh-left" @click="back">返回</el-button>
						<el-button v-if="titleList.length > 0" type="success" icon="el-icon-document"
							@click="seeWenJuan(wenjuanID,title)">预览</el-button>
						<el-button v-else type="primary" icon="el-icon-plus" @click="addTopic">新增问题</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div style="margin: 10px 50px;border: 1px solid #e8eaec;background-color: #FFFFFF;">
				<div v-cloak style="text-align:center;font-size:30px;">{{title}}</div>
				<div v-cloak style="text-align:center;font-size:20px">当前已出总题目数量：{{tltleLength}}</div>
				<div v-cloak v-if="titleList.length > 0" style="font-size:16px;margin-left:10%;">
					<div v-for="(item,index) in titleList" :key="index" style="margin: 20px 0;">
						<div>{{index+1}}、{{item.question_name}}</div>
						<img v-if="item.question_img" :src="item.question_img" width="200px" height="200px"
							style="border: #000000 1px solid;" />
						<div v-for="(choose,chooseIndex) in item.answers" :key="chooseIndex">
							<div v-if="item.question_class == 1">
								<el-radio-group v-model="item.choose" @change="changeRadio">
									<el-radio :label="choose.answer_name" :key="choose.answer_id">
										{{choose.answer_name}}
									</el-radio>
								</el-radio-group>
							</div>
							<div v-if="item.question_class == 2">
								<el-checkbox-group v-model="item.choose">
									<el-checkbox :label="choose.answer_name" :key="choose.answer_id">
										{{choose.answer_name}}
									</el-checkbox>
								</el-checkbox-group>
							</div>
							<div v-if="item.question_class == 3">
								<el-checkbox-group v-model="item.choose">
									<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
										placeholder="请输入您的意见" v-model="formData.name" style="width: 400px;">
									</el-input>
								</el-checkbox-group>
							</div>
						</div>
						<el-form :inline="true" ref="queryData" label-width="70px" label-position="right" size="mini"
							style="height: 35px;text-align:right;">
							<el-form-item>
								<el-tooltip class="item" effect="dark" content="新增问题" placement="bottom">
									<el-button type="warning" icon="el-icon-plus" circle @click="addTopic">
									</el-button>
								</el-tooltip>
								<el-tooltip class="item" effect="dark" content="编辑问题" placement="bottom">
									<el-button type="primary" icon="el-icon-edit" circle @click="updateTopic(item)">
									</el-button>
								</el-tooltip>
								<el-tooltip class="item" effect="dark" content="删除问题" placement="bottom">
									<el-button type="danger" icon="el-icon-delete" circle @click="delTopic(item)">
									</el-button>
								</el-tooltip>
							</el-form-item>
						</el-form>
					</div>
				</div>
			</div>
			<vxe-modal v-model="isShowModel" :title="isAddOrUpdate ? '新增问卷' : '编辑问卷' " :width="modelWith"
				@close="clseModel" show-zoom resize>
				<template #default>
					<el-form :model="formData" :rules="formRules" ref="ruleForm" label-width="100px"
						class="demo-ruleForm" style="padding: 20px 50px 0 50px;">
						<el-form-item label="题目类型" prop="type">
							<el-radio-group v-model="formData.type" :disabled="isAddOrUpdate ? false : true ">
								<el-radio v-for="(item,index) in typesList" :key="index" :label="item.value"
									style="margin:5px;">{{item.label}}
								</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="题目名称" prop="name">
							<el-input type="text" :autosize="{ minRows: 8, maxRows: 11}" placeholder="请输入题目名称"
								v-model="formData.name" style="width: 400px;">
							</el-input>
						</el-form-item>
						<el-form-item label="上传图片" prop="image">
							<el-upload class="upload-demo" :action="action" :limit="1" :headers="headers"
								:on-success="fileSuccessEvent" :on-preview="handlePreview" :on-remove="handleRemove"
								:file-list="formData.fileList" list-type="picture">
								<el-button size="small" type="primary">点击上传</el-button>
								<div slot="tip" class="el-upload__tip" style="color: red;">只能上传一张jpg/png文件，且不超过500KB
								</div>
							</el-upload>
						</el-form-item>
						<!-- <el-divider></el-divider> -->
						<el-form-item style="text-align: right;">
							<el-button type="primary" @click="submitForm('ruleForm')" size="mini" icon="el-icon-right">
								下一步</el-button>
							<el-button style="width:84.78px" @click="resetForm('ruleForm')" size="mini" type="warning"
								icon="el-icon-refresh">重置</el-button>
						</el-form-item>
						<!-- <el-form-item style="text-align: right;">
								<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
							</el-form-item> -->
					</el-form>
				</template>
			</vxe-modal>

			<vxe-modal v-model="isShowChooseModel" title="选择项添加" :width="answerWidth" show-zoom @close="clseChooseModel"
				resize>
				<template #default>
					<vxe-toolbar>
						<template #buttons>
							<vxe-button @click="insertEvent(-1)">新增答案选择</vxe-button>
							<vxe-button @click="$refs.xTable.removeCheckboxRow()">删除选中</vxe-button>
							<vxe-button type="submit" status="primary" @click="save" :loading="submitLoading">保存
							</vxe-button>
						</template>
					</vxe-toolbar>
					<vxe-table border show-overflow keep-source width="100%" ref="xTable" :data="tableData"
						:edit-rules="validRules" :header-cell-style="{'text-align':'center'}"
						:edit-config="{trigger: 'click', mode: 'cell', showStatus: true}"
						@radio-change="radioChangeEvent" @checkbox-change="selectChangeEvent" :loading="contentloading"
						:data="tableData" :loading-config="{icon: 'vxe-icon-indicator roll', text: '正在拼命加载中...'}">>
						<vxe-table-column type="checkbox" width="60" align="center"></vxe-table-column>
						<vxe-table-column type="seq" width="60" align="center"></vxe-table-column>
						<vxe-table-column field="answer_name" title="选项内容" width="577" :edit-render="{name: 'input'}">
						</vxe-table-column>
						<!-- <vxe-table-column field="answer_correct" title="是否正确答案" width="140">
							<template #render="scope">
								<vxe-radio v-model="scope.row.answer_correct" :label="true"></vxe-radio>
							</template>
						</vxe-table-column> -->

						<vxe-table-column field="answer_correct" title="是否正确答案" width="140" type="radio"
							v-if="topicType== '1'">
							<!-- <vxe-radio v-model="val1" :label="true"></vxe-radio> -->
						</vxe-table-column>
						<vxe-table-column :field="answerCorrectField" title="是否正确答案" width="140" v-if="topicType== '2'">
							<template #default="scope">
								<input type="checkbox" v-model="scope.row.checkbox1" @change="selectChangeEvent" />
							</template>
						</vxe-table-column>

					</vxe-table>
				</template>
			</vxe-modal>
		</el-main>
	</el-container>
</body>

<script type="text/javascript">
	window.onload = function () {
		var main = {
			data() {
				return {
					contentloading: false,
					submitLoading: false,
					val1: null,
					topicType: "",
					selectRow: null,
					title: null,
					tltleLength: 0,
					titleList: [],
					isShowModel: false,
					isAddOrUpdate: 1, // 1:新增   0:编辑
					dialogVisible: false,
					answerWidth: "868px",
					modelWith: '45%',
					modelHeight: '65%',
					formData: {
						type: '',
						name: '',
						fileList: []
					},
					formRules: {
						type: [{
							required: true,
							message: '请选择问题类型类型',
							trigger: 'blur'
						}],
						name: [{
							required: true,
							message: '请输入问题名称',
							trigger: 'change'
						}],
					},
					typesList: [{ 'value': '1', 'lable': '单选' }], //上传图片列表
					tableData: [
						{ answer_name: '选项1', is_correct: false, answer: "" },
						{ answer_name: '选项2', is_correct: false, answer: "" },
						// 添加更多选项数据
					],
					validRules: {
						answer: [{
							required: true,
							message: '选择项必须填写',
						}],
					},
					isShowChooseModel: false,
					wenjuanID: null,
					action: curl + '/attach/uploadAtt', //文件上传路径
					headers: { //设置上传的请求头部
						v_token: getCookie('v_token')
					},
					wentiID: ''
				}
			},
			created() {
				this.questionTypesList();
				this.wenjuanID = Tool.getParam("id")
				this.title = decodeURIComponent(Tool.getParam('name'))
				this.editExamPaper(this.wenjuanID)
			},
			mounted() {

			},
			computed: {
				answerCorrectField() {
					// 根据 topicType 决定要显示的列类型
					return this.topicType === '1' ? 'answer_correct_radio' : 'answer_correct_checkbox';
				},
			},
			methods: {
				columnType() {
					// 根据 topicType 返回相应的列类型
					return this.topicType === 1 ? 'radio' : this.topicType === 2 ? 'checkbox' : '';
				},
				editExamPaper(id) {
					let signParms = {
						id: id
					}
					let that = this;
					webApi('/wenjuan/editExamPaper?id=' + id, 'post', signParms, function (res) {
						if (res.code == 200) {
							let data = {}
							let arr = Object.keys(res.data)
							if (arr.length) {
								that.title = res.data[0].paper_name
								let list = res.data
								for (let i in list) {
									list[i].question_class == 1 || list[i].question_class == 3 ? list[i]['choose'] = null : list[i]['choose'] = []
								}
								that.titleList = []
								that.titleList = list
								// console.log("list", list);
								that.tltleLength = that.titleList.length
							} else {
								that.titleList = []
								that.tltleLength = 0
							}
							setTimeout(() => {
								that.titleList.length ? '' : that.addTopic()
							}, 300)

						} else {
							that.$message({
								message: res.msg,
								type: 'error'
							})
						}

					}, function (xhr, type, errorThrown) { });

				},
				addTopic() {
					this.tableData = [{
						answer_name: '请输入答案',
						answer_correct: false, // 设置为 true 表示正确答案
						answer: ""
					},
					{
						answer_name: '请输入答案',
						answer_correct: false, // 设置为 false 表示错误答案
						answer: ""
					},
					]
					this.$refs.xTable.afterFullData = {}
					this.isShowModel = true
					this.isAddOrUpdate = 1
				},
				radioChangeEvent({ row }) {


					this.selectRow = row;
					this.$set(row, 'answer_correct', !row.answer_correct);
					row.answer = row.answer_correct ? 1 : "";

					const allRecord = this.$refs.xTable.afterFullData;
					allRecord.forEach(record => {
						if (record !== row && record.answer_correct) {
							record.answer_correct = false;
							record.answer = "";
						}
					});
					// console.log("allRecord", allRecord);
					// console.log('单选事件', row)
					// console.log('this.tableData', this.tableData)

				},

				selectChangeEvent() {
					// console.log(111);
					const allRecords = this.$refs.xTable.afterFullData;
					allRecords.forEach(record => {
						if (record.checkbox1) {
							record.answer_correct = true;
							record.answer = 1;
						} else {
							record.answer_correct = false;
							record.answer = '';
						}
					});
					// console.log("allRecords", allRecords)

				},

				updateTopic(item) {
					// console.log("item", item);
					this.tableData = []
					this.$refs.xTable.afterFullData = {}
					for (let i in item.answers) {
						let data = this.getCaption(item.answers[i].answer_name, 1)
						this.tableData.push({
							'answer_id': item.answers[i].answer_id,
							'answer_name': data
						})
					}
					this.formData.type = item.question_class
					this.formData.name = item.question_name
					if (item.question_img) {
						this.formData.fileList = [{
							name: '',
							url: item.question_img
						}]
					}
					this.wentiID = item.question_id
					this.isShowModel = true;
					this.isAddOrUpdate = 0
				},
				delTopic(item) {
					let that = this;
					let apiUrlMethod = `/wenjuan/deleteQuestionFromPaper?paperId=${item.paper_id}`;
					let params = {
						id: item.question_id,
					}
					this.$XModal.confirm('确定要删除该数据？').then(type => {
						if (type == 'confirm') {
							webApi(apiUrlMethod, 'post', params, function (res) {
								if (res.code == 200) {
									that.$message({
										message: res.msg,
										type: 'success'
									})
									that.editExamPaper(that.wenjuanID)
								} else {
									that.$message({
										message: res.msg,
										type: 'error'
									})
								}

							}, function (xhr, type, errorThrown) { });
						}
					})
				},
				questionTypesList() {
					let params = {
						dictId: 22
					};
					let that = this
					webApi('/dict/getDictDetailTreeList', 'post', params, function (res) {
						if (res.code == 200) {
							let length = []
							length = res.data
							if (length < 1) {
								that.$message({
									message: '暂无字典表数据',
									type: 'warning'
								})
							} else {
								that.typesList = res.data
							}
						} else {
							that.$message({
								message: res.msg,
								type: 'warning'
							})
						}

					}, function (xhr, type, errorThrown) { })
				},
				submitForm(formName) {
					this.$refs[formName].validate((valid) => {
						if (valid) {
							if (this.isAddOrUpdate) {
								console.log("this.topicType", this.topicType);

								this.isShowModel = false
								this.isShowChooseModel = true

								this.topicType = this.formData.type

							} else {
								// console.log(1111);
								this.isShowModel = false
								this.isShowChooseModel = true
								this.topicType = this.formData.type
								console.log("this.topicType", this.topicType);
								this.$refs.xTable.afterFullData = {}
								this.$refs.xTable.loadData(this.tableData);
							}
						} else {
							return false;
						}
					});
					// console.log(this.topicType, 222);
				},
				resetForm(formName) {
					this.$refs[formName].resetFields();
				},
				handleRemove(file, fileList) {
					//console.log(file, fileList);
					this.formData.fileList = []
				},
				handlePreview(file) {
					//console.log(file);
				},
				async insertEvent(row) {
					if (this.$refs.xTable.afterFullData.length < 4) {
						const $table = this.$refs.xTable
						const record = {}
						const {
							row: newRow
						} = await $table.insertAt(record, row)
					} else {
						this.$message({
							message: "最多只支持四个选项",
							type: 'warning'
						})
					}
				},
				save() {
					let index = null
					let flag = true
					let that = this;
					for (let i in this.$refs.xTable.afterFullData) {
						if (this.$refs.xTable.afterFullData[i].answer_name == "" || this.$refs.xTable
							.afterFullData[i]
							.answer_name == null) {
							index = Number(i) + Number(1)
							this.$message({
								message: '请填写第' + index + '的选项内容',
								type: 'warning'
							})
							flag = false
							break;
						}
					}

					if (flag) {
						let chooseData = []
						for (let i in this.$refs.xTable.afterFullData) {
							// console.log("this.$refs.xTable.afterFullData", this.$refs.xTable.afterFullData);
							chooseData.push({
								// answer: this.isAddOrUpdate ? "" : this.$refs.xTable.afterFullData[i]
								// 	.answer,
								answer: this.$refs.xTable.afterFullData[i]
									.answer,
								answerName: this.$refs.xTable.afterFullData[i].answer_name,

							})
						}
						let params = {
							answers: chooseData,
							paperId: this.wenjuanID,
							questionClass: this.formData.type, //题目类型
							questionId: this.isAddOrUpdate ? "" : this.wentiID,
							questionImg: this.formData.fileList.length ? this.formData.fileList[0].url : "",
							questionName: this.formData.name, //题目名称
						}
						// console.log("this.wenjuanID", this.wenjuanID);
						if (this.isAddOrUpdate) {

							that.contentloading = true
							XEAjax.post(`${curl}/wenjuan/questionAdd`, params).then(res => {	// that.submitLoading = false;
								that.contentloading = false
								if (res.code == 200) {
									that.$message({
										message: res.msg,
										type: 'success'
									})
									that.isShowChooseModel = false
									that.formData = {
										type: '',
										name: '',
										fileList: []
									}
									that.tableData = [{
										answer_name: '同意',
									},
									{
										answer_name: '不同意',
									},
									]
									that.$refs.xTable.afterFullData = {}
									that.editExamPaper(that.wenjuanID)
								} else {
									that.$message({
										message: res.msg,
										type: 'error'
									})
								}
							});
						} else {
							// that.submitLoading = true;
							that.contentloading = true
							webApi('/wenjuan/questionUpdate', 'post', params, function (res) {
								// that.submitLoading = false;
								that.contentloading = false
								if (res.code == 200) {
									that.$message({
										message: res.msg,
										type: 'success'
									})
									that.isShowChooseModel = false
									that.formData = {
										type: '',
										name: '',
										fileList: []
									}
									that.tableData = [{
										answer_name: '同意',
									},
									{
										answer_name: '不同意',
									},
									]
									that.$refs.xTable.afterFullData = {}
									that.editExamPaper(that.wenjuanID)
								} else {
									that.$message({
										message: res.msg,
										type: 'error'
									})
								}

							}, function (xhr, type, errorThrown) { });
						}
					}
				},
				clseModel() {
					this.formData = {
						type: '',
						name: '',
						fileList: []
					}
					this.tableData = [{
						answer_name: '同意',
					},
					{
						answer_name: '不同意',
					},
					]
					//this.$refs.xTable.afterFullData = {}
					this.$refs.xTable.loadData(this.tableData);
				},
				clseChooseModel() {
					this.formData = {
						type: '',
						name: '',
						fileList: []
					}
					this.tableData = [{
						answer_name: '同意',
					},
					{
						answer_name: '不同意',
					},
					]
					this.$refs.xTable.afterFullData = {}
					//console.log(this.$refs.xTable.afterFullData)
					this.$refs.xTable.loadData(this.tableData);
				},
				getCaption(obj, state) {
					var index = obj.lastIndexOf(".");
					if (state == 0) {
						obj = obj.substring(0, index);
					} else {
						obj = obj.substring(index + 1, obj.length);
					}
					return obj;
				},
				back() {
					setTimeout(() => {
						Tool.openTabEvent('../question/wenjuanManagement.html', '问卷管理');
					}, 300)
				},
				seeWenJuan(id, paper_name) {
					setTimeout(() => {
						Tool.openTabEvent('../question/seeWenJuan.html', '问卷预览', {
							'id': id,
							'name': encodeURIComponent(paper_name)
						});
					}, 300)
				},
				fileSuccessEvent(res, file, fileList) {
					// this.fullscreenLoading = true;
					if (res.code == 200) {
						this.$message({
							message: res.msg,
							type: 'success'
						})
						//this.formData.fileList = []
						this.formData.fileList.push({
							name: res.data.original,
							url: res.data.url
						})
					} else {
						this.$message({
							message: res.data.state,
							type: 'error'
						})
					}
				},
				changeRadio(e) {
					console.log(e)
				}
			}
		};
		var vue = Vue.extend(main);
		new vue().$mount('#app');
	}
</script>

</html>